package com.herench.bunch.commons.support;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

public class SimpleMessageHandlerServicePool implements ServicePool<String, MessageHandler> {

    private static final Logger logger = LoggerFactory.getLogger(SimpleMessageHandlerServicePool.class);


    protected final ConcurrentMap<String, MessageHandler> pool = new ConcurrentHashMap<>();


    @Override
    public MessageHandler addAndAcquire(String msgCode, MessageHandler messageHandler) {
        MessageHandler handler = pool.get(msgCode);
        if (handler != null) {
            throw new RuntimeException(msgCode + " messageHandler已经存在.");
        }
        pool.put(msgCode, messageHandler);
        if (logger.isInfoEnabled()) {
            logger.info(msgCode + " messageHandler已注册..");
        }
        return messageHandler;
    }

    @Override
    public MessageHandler acquire(String msgCode) {
        MessageHandler answer = pool.get(msgCode);
        return answer;
    }

    @Override
    public void release(String msgCode, MessageHandler messageHandler) {
        pool.put(msgCode, messageHandler);
        if (logger.isInfoEnabled()) {
            logger.info(msgCode + " messageHandler已注册..");
        }
    }

    @Override
    public boolean remove(String msgCode) {
        MessageHandler remove = pool.remove(msgCode);
        if (logger.isInfoEnabled()) {
            logger.info(msgCode + " messageHandler已注销..");
        }
        return remove != null;
    }

    @Override
    public boolean isExist(String msgCode) {
        return pool.containsKey(msgCode);
    }

    @Override
    public int size() {
        return this.pool.size();
    }

    @Override
    public void purge() {
        this.pool.clear();
    }

    @Override
    public List<MessageHandler> getServices() {
        List<MessageHandler> services = new ArrayList<>();
        for (Map.Entry<String, MessageHandler> entry : this.pool.entrySet()) {
            services.add(entry.getValue());
        }
        return services;
    }

}